//
//  QDQuesPhotoTableViewCell.swift
//  QDMetroClient
//
//  Created by YueWen on 2019/3/3.
//  Copyright © 2019 YueWen. All rights reserved.
//

/// 又是一个需要重构的代码


import UIKit

protocol QDQuesPhotoTableViewCellDelegate: class {
    
    /// 照片cell进行的操作
    func quesPhotoTableViewCell(cell: QDQuesPhotoTableViewCell,action: QDQuesPhotoTableViewCell.PhotoActionType, at indexPath:IndexPath)
}

extension QDQuesPhotoTableViewCellDelegate {
    
    func quesPhotoTableViewCell(cell: QDQuesPhotoTableViewCell,action: QDQuesPhotoTableViewCell.PhotoActionType, at indexPath:IndexPath){}
}

/// 图片视图
final class QDQuesPhotoCollectionViewCell: NWCollectionViewCell {
    
    /// 图片
    let imageView = UIImageView()
    /// 关闭按钮
    let closeButton = UIButton()
    /// 关闭按钮进行点击
    var closeButtonTapHandler: (()->())?
    
    override func buildView() {
        super.buildView()
        
        imageView.backgroundColor = #colorLiteral(red: 0.9803921569, green: 0.9882352941, blue: 0.9803921569, alpha: 1)
        imageView.layer.cornerRadius = 4
        imageView.layer.borderColor = #colorLiteral(red: 0.8901960784, green: 0.9019607843, blue: 0.8941176471, alpha: 1)
        imageView.layer.borderWidth = 0.5
        imageView.clipsToBounds = true
        imageView.contentMode = .scaleAspectFit
        
        closeButton.adjustsImageWhenHighlighted = false
        closeButton.setImage("ques_close".namedImage, for: .normal)
        
        contentView.addSubview(imageView)
        contentView.addSubview(closeButton)
        
        imageView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        closeButton.snp.makeConstraints { (make) in
            make.right.top.equalToSuperview()
            make.width.height.equalTo(20)
        }
        
        closeButton.controlEvents(.touchUpInside) { [unowned self](_) in
            self.closeButtonTapHandler?()
        }
    }
}

/// 问题描述 相关问题截图
final class QDQuesPhotoTableViewCell: NWTableViewCell,QDQuesFeedTableViewCell {

    /// 图片操作类型
    enum PhotoActionType {
        /// 添加
        case add
        /// 删除
        case remove
    }
    
    
    /// 计算item的大小
    static var itemSize: Int {
        get {
            return UIScreen.main.ritl_width > 370 ? 80 : Int((UIScreen.main.ritl_width - 40 - 3) / 4)
        }
    }
    
    /// 显示标题
    let titleLabel = UILabel()

    /// item的大小
    var itemSize: Int {
        get {
            return QDQuesPhotoTableViewCell.itemSize
        }
    }
    
    /// 图片的数组
    var images = [UIImage]() {
        didSet {
            if oldValue == images { return }
            countLabel.text = "\(images.count)/3"
            collectionView.reloadData()
        }
    }
    
    /// 代理对象
    weak var photoDelegate: QDQuesPhotoTableViewCellDelegate?
    
    /// 显示个数
    private let countLabel = UILabel()
    /// 集合布局
    private lazy var flowLayout: UICollectionViewFlowLayout = {
        
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.sectionInset.left = 20
        flowLayout.sectionInset.right = 20
        flowLayout.itemSize = CGSize(width: itemSize, height: itemSize)
        flowLayout.scrollDirection = .horizontal
        flowLayout.minimumLineSpacing = ((UIScreen.main.ritl_width - CGFloat(4 * itemSize)) - 40) / CGFloat(3)
        flowLayout.minimumInteritemSpacing = .leastNormalMagnitude
        return flowLayout
    }()
    /// 展示集合视图
    private lazy var collectionView: UICollectionView = {
        return UICollectionView(frame: .zero, collectionViewLayout: flowLayout)
    }()
    
    override func buildView() {
        super.buildView()

        titleLabel.text = "上传图片"
        initTitleLabel()
        makeConstraintsForTitleLabel()
        
        countLabel.text = "0/3"
        countLabel.font = Font.regular.font(size: 14)
        countLabel.textColor = QDColors.gray
        
        collectionView.backgroundColor = .white
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.register(QDQuesPhotoCollectionViewCell.self, forCellWithReuseIdentifier: "cell")
        
        contentView.addSubview(countLabel)
        contentView.addSubview(collectionView)
        
        countLabel.snp.makeConstraints { (make) in
            make.right.equalToSuperview().inset(20)
            make.centerY.equalTo(titleLabel)
            make.height.equalTo(17)
        }
        
        collectionView.snp.makeConstraints { (make) in
            make.top.equalTo(titleLabel.snp.bottom).offset(16)
            make.left.right.equalTo(0)
            make.bottom.equalToSuperview().inset(32)
        }
    }
}


extension QDQuesPhotoTableViewCell: UICollectionViewDataSource,UICollectionViewDelegate {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return min(max(images.count + 1, 1), 3)
    }
    
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
        
        guard let imageCell = cell as? QDQuesPhotoCollectionViewCell else {
            return cell
        }

        if images.count == 0 {//如果不存在
            imageCell.imageView.image = "ques_image".namedImage
            imageCell.closeButton.isHidden = true
            
        }else if images.count < 3 { //如果在中间
            
            let isPhoto = (images.count > indexPath.item)
            imageCell.imageView.image = isPhoto ? images[indexPath.item] : "ques_image".namedImage
            imageCell.closeButton.isHidden = !isPhoto
            
        } else {
            imageCell.imageView.image = images[indexPath.item]
            imageCell.closeButton.isHidden = false
        }

        //设置block
        imageCell.closeButtonTapHandler = { [unowned self] in
            self.photoDelegate?.quesPhotoTableViewCell(cell: self, action: .remove, at: indexPath)
        }
        
        return cell
    }
    
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        if indexPath.item == images.count {
             photoDelegate?.quesPhotoTableViewCell(cell: self, action: .add, at: indexPath)
        }
    }
}
